import math
import sys
import time
import torch

import torchvision.models.detection.mask_rcnn

from utility.coco_utils import get_coco_api_from_dataset
from utility.coco_eval import CocoEvaluator
import utility.utils as utils


def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq):
    model.train()
    metric_logger = utils.MetricLogger(delimiter="  ")
    metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))
    header = 'Epoch: [{}]'.format(epoch)

    lr_scheduler = None
    if epoch == 0:
        warmup_factor = 1. / 1000
        warmup_iters = min(1000, len(data_loader) - 1)

        lr_scheduler = utils.warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor)

    for images, targets in metric_logger.log_every(data_loader, print_freq, header):
        images = list(image.to(device) for image in images)
        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]

        loss_dict = model(images, targets)

        losses = sum(loss for loss in loss_dict.values())

        # reduce losses over all GPUs for logging purposes
        loss_dict_reduced = utils.reduce_dict(loss_dict)
        losses_reduced = sum(loss for loss in loss_dict_reduced.values())

        loss_value = losses_reduced.item()

        if not math.isfinite(loss_value):
            print("Loss is {}, stopping training".format(loss_value))
            print(loss_dict_reduced)
            sys.exit(1)

        optimizer.zero_grad()
        losses.backward()
        optimizer.step()

        if lr_scheduler is not None:
            lr_scheduler.step()

        metric_logger.update(loss=losses_reduced, **loss_dict_reduced)
        metric_logger.update(lr=optimizer.param_groups[0]["lr"])


def _get_iou_types(model):
    model_without_ddp = model
    if isinstance(model, torch.nn.parallel.DistributedDataParallel):
        model_without_ddp = model.module
    iou_types = ["bbox"]
    if isinstance(model_without_ddp, torchvision.models.detection.MaskRCNN):
        iou_types.append("segm")
    if isinstance(model_without_ddp, torchvision.models.detection.KeypointRCNN):
        iou_types.append("keypoints")
    return iou_types


@torch.no_grad()
def evaluate(model, data_loader, device):
    """评估模型性能
    Args:
        model: 要评估的模型
        data_loader: 数据加载器
        device: 计算设备 (cpu/gpu)
    Returns:
        coco_evaluator: 包含评估结果的对象
    """
    # 保存当前线程数并设置为1（为了兼容性）
    n_threads = torch.get_num_threads()
    torch.set_num_threads(1)
    
    # 初始化CPU设备
    cpu_device = torch.device("cpu")
    
    # 将模型设置为评估模式
    model.eval()
    
    # 初始化日志记录器
    metric_logger = utils.MetricLogger(delimiter="  ")
    header = 'Test:'

    # 从数据集中获取COCO API
    coco = get_coco_api_from_dataset(data_loader.dataset)
    
    # 获取模型支持的IOU类型（bbox/segm/keypoints）
    iou_types = _get_iou_types(model)
    
    # 初始化COCO评估器
    coco_evaluator = CocoEvaluator(coco, iou_types)

    # 遍历数据加载器
    for image, targets in metric_logger.log_every(data_loader, 100, header):
        # 将图像和目标移动到指定设备
        image = list(img.to(device) for img in image)
        targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 
        # 同步CUDA设备（如果使用GPU）
        torch.cuda.synchronize()
        
        # 记录模型推理时间
        model_time = time.time()
        
        # 模型推理
        outputs = model(image)
        
        # 修改：直接在GPU上处理结果
        outputs = [{k: v for k, v in t.items()} for t in outputs]
#    outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs]
        model_time = time.time() - model_time

        # 准备评估结果
        res = {target["image_id"].item(): output for target, output in zip(targets, outputs)}
        
        # 修改：将结果移动到CPU进行评估（COCO评估器需要CPU数据）
        res_cpu = {k: {k2: v2.cpu() for k2, v2 in v.items()} for k, v in res.items()}
        
        # 记录评估时间并更新评估器
        evaluator_time = time.time()
        coco_evaluator.update(res_cpu)
        evaluator_time = time.time() - evaluator_time
        
        # 更新日志
        metric_logger.update(model_time=model_time, evaluator_time=evaluator_time)

    # 同步所有进程的统计信息
    metric_logger.synchronize_between_processes()
    print("Averaged stats:", metric_logger)
    
    # 同步评估器
    coco_evaluator.synchronize_between_processes()

    # 累积所有图像的预测结果
    coco_evaluator.accumulate()
    
    # 输出评估总结
    coco_evaluator.summarize()
    
    # 恢复原始线程数
    torch.set_num_threads(n_threads)
    
    return coco_evaluator
